import styles from './index.module.less'
import { useCallback, useState } from 'react'
import { ZoomIn, ZoomOut, Undo, Redo, Scan, Edit } from '@terminus/nusi-slim-icons'
import { Tooltip } from '@terminus/nusi-slim'
import clsx from 'clsx'
import { useProcessMiningEngineStore } from '../store'

const Toolbar = () => {
	const graph = useProcessMiningEngineStore((state) => state.graph)

	const [enableMultiSelect, setEnableMultiSelect] = useState(false)

	// 撤销
	const undo = useCallback(() => {
		graph?.undo?.()
	}, [graph])

	// 重做
	const redo = useCallback(() => {
		graph?.redo?.()
	}, [graph])

	// 放大
	const zoomIn = useCallback(() => {
		const zoom = graph?.zoom?.() || 1
		if (zoom < 1.5) {
			graph?.zoom(0.1)
		}
	}, [graph])

	// 缩小
	const zoomOut = useCallback(() => {
		const zoom = graph?.zoom?.() || 1
		if (zoom > 0.5) {
			graph?.zoom(-0.1)
		}
	}, [graph])

	// 开启框选
	const toggleSelect = useCallback(() => {
		// 是否开启拖动画布
		const pannable = graph?.panning?.pannable
		
		if(pannable) {
			graph?.disablePanning()
			graph?.enableRubberband()
			setEnableMultiSelect(true)
		} else {
			graph?.enablePanning()
			graph?.disableRubberband()
			setEnableMultiSelect(false)
		}
	}, [graph])

	// 适配页面
	const fitToContent = useCallback(() => {
		if (!graph) return
		// 获取画布中的所有节点和边
		const cells = graph.getCells()
		if (cells.length === 0) return

		// 使用 zoomToFit 方法适配所有内容
		graph.zoomToFit({
			padding: 20, // 边距
			maxScale: 1, // 最大缩放比例
			minScale: 0.1, // 最小缩放比例
		})
	}, [graph])

	const toolList = [
		{
			icon: <Edit size="16px" />,
			active: enableMultiSelect,
			title: enableMultiSelect ? '关闭框选' : '开启框选',
			onClick: toggleSelect,
			hidden: true,
		},
		{
			icon: <Undo size="16px" />,
			title: '撤销',
			onClick: undo,
			hidden: true,
		},
		{
			icon: <Redo size="16px" />,
			title: '重做',
			onClick: redo,
			hidden: true,
		},
		{
			icon: <ZoomIn size="16px" />,
			title: '放大',
			onClick: zoomIn,
		},
		{
			icon: <ZoomOut size="16px" />,
			title: '缩小',
			onClick: zoomOut,
		},
		{
			icon: <Scan size="16px" />,
			title: '适配页面',
			onClick: fitToContent,
		},
	]

  return (
    <div className={styles.toolbar}>
			{toolList.filter((item) => !item.hidden).map((item, index) => (
				<Tooltip key={index} title={item.title}>
					<div className={clsx(styles.toolbarItem, item.active && styles.active)} onClick={item.onClick}>
						{item.icon}
					</div>
				</Tooltip>
			))}
    </div>
  )
}

export default Toolbar